package tgc.edu.exam.web.controller;

import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.custom.dict.entity.SystemData;
import tgc.edu.exam.custom.dict.entity.SystemDictionaries;
import tgc.edu.exam.custom.dict.service.SystemDataService;
import tgc.edu.exam.custom.dict.service.SystemDicationariesService;
import tgc.edu.exam.entity.TbCurriculum;
import tgc.edu.exam.service.TeacherService;
import tgc.edu.exam.web.form.TbCurriculumForm;

@Controller
@RequestMapping(value="/tbCurriculum")
public class TbCurriculumController extends CommonController<TbCurriculum, UUID, TbCurriculumForm> {
	@Autowired
	private SystemDicationariesService dictService;
	@Autowired
	private SystemDataService dataService;
	@Autowired
	private TeacherService tcService;

	@Override
	public Specification<TbCurriculum> buildSpec(TbCurriculumForm form) {
		Specification<TbCurriculum> specification = new Specification<TbCurriculum>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<TbCurriculum> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getCourseName())) {
					Predicate name = cb.like(root.get("courseName"), "%"+form.getCourseName()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getDifficultylevel())) {
					Predicate difficultylevel = cb.like(root.get("difficultylevel"), "%"+form.getDifficultylevel()+"%");
					rules.add(difficultylevel);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}

	@Override
	public void edit(TbCurriculumForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		SystemDictionaries systemDictionaries = dictService.findByCode("facility_value");
		List<SystemData> data = dataService.findBySystemDictionaries(systemDictionaries);
		map.put("data", data);
		SystemDictionaries systemDictionaries1 = dictService.findByCode("kcfl");
		List<SystemData> data1 = dataService.findBySystemDictionaries(systemDictionaries1);
		map.put("data1", data1);
		map.put("teacher", tcService.findAll());
		super.edit(form, map);
	}
	

}
